/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import ejb.EmailSender;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
import javax.ejb.EJB;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import service.MumuUser;
import service.MumuUserFacadeREST;
import utilities.ReadSmtp;

/**
 *
 * @author andrew
 */
@WebServlet(name = "RequestAccessServlet", urlPatterns = {"/RequestAccessServlet"})
public class RequestAccessServlet extends HttpServlet {

    @EJB
    private EmailSender mailManager;
    
    @EJB
    private MumuUserFacadeREST userManager;
    
    private Session session;
    
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String nameSurname = request.getParameter("name_surname");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        password = encrypt(password);
        String qualification = request.getParameter("qualification");
        
        boolean canSendMail = true;
        
        final ReadSmtp readSmtp = new ReadSmtp(request);
        
        Collection<MumuUser> collUser = userManager.findAll();
        Iterator<MumuUser> itUser = collUser.iterator();
        while(itUser.hasNext()){
            MumuUser u = itUser.next();
            if(u.getMail().equals(email)){
                canSendMail = false;
            }
        }
        
        
        if(canSendMail){
            String grantUrl = request.getRequestURL().toString().replace("RequestAccessServlet", "home.jsp");
            grantUrl += "?nameSurname=" + URLEncoder.encode(nameSurname, "UTF-8") + "&email=" + email;

            mailManager.requestAccess(nameSurname, email, password, qualification, grantUrl, request);

            // manda msg che la richiesta è stata inviata con successo
            response.sendRedirect("/home.jsp?status=1");
            
            // invio mail di notifica che la richiesta di registrazione è stata presa i carico
            Properties props = new Properties();
            props.put("mail.smtp.host", readSmtp.getSmtp_address());
            props.put("mail.smtp.socketFactory.port", readSmtp.getSmtp_port());
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", readSmtp.getAuth());
            props.put("mail.smtp.port", readSmtp.getSmtp_port());

            session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            // email address e password
                            
                            
                            return new PasswordAuthentication(readSmtp.getAuth_username(), readSmtp.getAuth_password());
                        }
                    });

            try {
                
                InternetAddress from = new InternetAddress( email, "UniverseCreator" );
                
                Message message = new MimeMessage(session);
                message.setFrom(from);
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
                message.setSubject("UniverseCreator: richiesta di registrazione ricevuta");
                String content = "Gentile " + nameSurname + ",<br/><br/>"
                        + "La richiesta di registrazione da te inviata a UniverseCreator &egrave; stata trasmessa agli amministratori.<br/>"
                        + "<br/>"
                        + "Riceverai un messaggio di notifica non appena la tua richiesta sar&agrave; stata evasa."
                        + "<br/><br/><br/>"
                        + "<i>Staff di UniverseCreator</i>"
                        + "<br/><br/><br/>"
                        + "Non rispondere, messaggio generato in automatico da UniverseCreator.<br/>";
                message.setContent(content, "text/html");
                Transport.send(message);
            } catch (Exception e) {
                System.err.println(e.getCause());
            }
            
        }else{
            // esiste già uno con la stessa mail
            response.sendRedirect("/home.jsp?error=2");
        }
        
    }
    private String encrypt(String password){
        MessageDigest m = null;
        try {
            m = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ex) {
            System.err.println(ex.getMessage());
        }
        m.update(password.getBytes(), 0, password.length());
        return new BigInteger(1, m.digest()).toString(16);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
        
//        // check if session is expired
//        HttpSession session = request.getSession(false);// don't create if it doesn't exist
//        if(session != null && !session.isNew()) {         
//            processRequest(request, response);
//        } else {
//            response.sendRedirect("/home.jsp");
//        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
        
//        // check if session is expired
//        HttpSession session = request.getSession(false);// don't create if it doesn't exist
//        if(session != null && !session.isNew()) {         
//            processRequest(request, response);
//        } else {
//            response.sendRedirect("/home.jsp");
//        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }
}
